// https://leetcode.cn/problems/rearrange-spaces-between-words/
// Created by ade on 2022/9/7.
//
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

class Solution {
public:
    string reorderSpaces(string text) {
        int spc = count(text.cbegin(), text.cend(), ' ');

        stringstream ss(text);
        string tmp = "";
        vector <string> res = {};
        while (getline(ss, tmp, ' ')) {
            if (tmp != "") {
                res.push_back(tmp);
            }
        }
        int wordLen = res.size();
        string ans = "";
        if (wordLen == 1) {
            ans = res[0] + string(spc, ' ');
        } else {
            for (auto &i : res) {
                ans += i + string(spc / (wordLen - 1), ' ');
            }
            if (spc % (wordLen - 1) == 0) {
                ans = ans.substr(0, ans.size() - spc / (wordLen - 1));
            } else {
                ans = ans.substr(0, ans.size() - spc / (wordLen - 1)) + string(spc % (wordLen - 1), ' ');
            }
        }
        return ans;
    }
};

int main() {
    Solution so;
    cout << so.reorderSpaces("  this   is  a sentence  ") << endl;
    return 0;
}